#ifndef __FILEPROCESSOR_H__
#define __FILEPROCESSOR_H__

#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <regex>
#include <tinyxml2.h>

using namespace::tinyxml2;
using std::string;
using std::vector;
using std::cout;
using std::endl;
using std::regex;
using std::ostringstream;

struct RssItem {
    string title;
    string link;
    string content;
};

class FileProcessor
{
public:
    FileProcessor() {

    }
    // ~FileProcessor() {

    // }

    void process(string &filename, vector<string> &files) {
        parseRss(filename);
        dump(files);
    }

    void clearVec() {
        _rss.clear();
    }

    void parseRss(string &filename) {
        XMLDocument xml;
        if (xml.LoadFile(filename.c_str())) {
            xml.PrintError();
            exit(-1);
        }

        XMLElement *category = xml.RootElement();
        XMLElement *channel = category->FirstChildElement("channel");
        XMLElement *title = channel->FirstChildElement("title");
        XMLElement *item = channel->FirstChildElement("item");
        while (item) {
            RssItem rss_item;

            regex reg("<[^>]*>");

            XMLElement *item_title = item->FirstChildElement("title");
            rss_item.title = item_title->GetText();
            XMLElement *item_link = item->FirstChildElement("link");
            rss_item.link = item_link->GetText();
            XMLElement *item_description = item->FirstChildElement("description");
            rss_item.content = item_description->GetText();
            rss_item.content = regex_replace(rss_item.content, reg, "");

            _rss.push_back(rss_item);

            item = item->NextSiblingElement();
        }
    }
    void dump(vector<string> &files) {
        for (int i = 0; i != _rss.size(); ++i) {
            ostringstream oss;
            oss << "<doc>" << endl
                << "\t" << "<docid>" << files.size() + 1 << "</docid>" << endl
                << "\t" << "<title>" << _rss[i].title << "</title>" << endl
                << "\t" << "<link>"  << _rss[i].link  << "</link>"  << endl
                << "\t" << "<content>" << _rss[i].content << "</content>" << endl
                << "</doc>" << endl;
            files.push_back(oss.str());
        }
    }

private:
    vector<RssItem> _rss;
};

#endif
